package com.banksoft.cps.util;

import com.banksoft.cps.bean.User;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * Created by rongzhao.zhu on 2017/12/16.
 */
public class CacheUtil {

    private static Cache<String, User> userCache = CacheBuilder.newBuilder()
            //设置cache的初始大小为10，要合理设置该值
            .initialCapacity(1000)
            //设置并发数为5，即同一时间最多只能有5个线程往cache执行写入操作
            .concurrencyLevel(100)
            //设置cache中的数据在写入之后的存活时间为10分钟
            .expireAfterAccess(100, TimeUnit.MINUTES)
            //构建cache实例
            .build();

    public static void cache(String key,User user){
        userCache.put(key,user);
    }
    public static User getByKey(String key){
        if(StringUtils.isBlank(key)){
            return null;
        }
        return userCache.getIfPresent(key);
    }
    public static void remove(String key){
        userCache.invalidate(key);
    }
}
